package com.g2room.driving.util;

import java.io.File;
import java.io.IOException;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;

public class QiniuFileOp {
	//设置好账号的ACCESS_KEY和SECRET_KEY
	final static String ACCESS_KEY = "yz_eu4PN4dC0ctRWSPCWwOUabPdugvWPaAP2fjRV";
	final static String SECRET_KEY = "F8Fe5fYILY9hzjVusoPrpBX3W1qFbtJDi1vg3W1-";
	//密钥配置
	static Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
	//创建上传对象
	static UploadManager uploadManager = new UploadManager();
	static String localFileDir;
	static String bucket;

//	//简单上传，使用默认策略，只需要设置上传的空间名就可以了
//	public String getUpToken(){
//		return auth.uploadToken(bucketname);
//	}
	
	// 覆盖上传
	public static String getUpToken(String bucket, String filename){
		//<bucket>:<key>，表示只允许用户上传指定key的文件。在这种格式下文件默认允许“修改”，已存在同名资源则会被本次覆盖。
		//如果希望只能上传指定key的文件，并且不允许修改，那么可以将下面的 insertOnly 属性值设为 1。
		//第三个参数是token的过期时间
		return auth.uploadToken(bucket, filename, 3600, new StringMap().put("insertOnly", 0));
	}

	/**
	 * 上传文件
	 * @param localFilePath	本地文件地址
	 * @param bucket	七牛bucket
	 * @param filename	文件名，带后缀
	 * @throws IOException
	 */
	public static void upload(String localFilePath, String bucket, String filename) {
		try {
			//调用put方法上传
			uploadManager.put(localFilePath, filename, getUpToken(bucket, filename));
//			Response res = uploadManager.put(localFilePath, filename, getUpToken(bucket, filename));
//			//打印返回的信息
//			System.out.print(res.bodyString() + "     "); 
		} catch (QiniuException e) {
			Response r = e.response;
			// 请求失败时打印的异常的信息
			System.out.println(r.toString());
			try {
				//响应的文本信息
				System.out.println(r.bodyString());
			} catch (QiniuException e1) {
				//ignore
			}
		}       
	}
	
	private static void uploadDir(File f, String dir) {
		if (f.isDirectory()) {
			for (File file : f.listFiles()) {
				uploadDir(file, (f.getName().equals(HtmlUtil.getDateDir())?null : f.getName()));
			}
		} else {
			upload(f.getPath(), bucket, (null == dir ? "" : (dir + "/")) + f.getName());
		}
	}
	
	/**
	 * 上传文件到七牛存储空间
	 * @param path	本地文件夹路径
	 * @param bucketname	七牛空间名称
	 */
	public static void uploadDir(String path, String bucketname) {
		bucket = bucketname;
		localFileDir = path;
		uploadDir(new File(path), null);
	}
	
	public static void main(String args[]) throws IOException{  
		upload("E:/高绪国/资料/images/qgsh/sourceImg/20160512/ys/115957942747379pz6pPB.jpg", "1nsh-web", "1.jpg");
	}

}
